var AMZ = function () {};

AMZ.prototype.init = function () {
  LocalContractStorage.set('AMZ', JSON.stringify(21000000));
  LocalContractStorage.set('tokenArr', JSON.stringify(['AMZ']));
}

AMZ.prototype.getUserInfo = function () {
  var address = Blockchain.transaction.from;
  return LocalContractStorage.get(address);
}

AMZ.prototype.register = function () {
  var address = Blockchain.transaction.from;
  var amzAssets = JSON.parse(LocalContractStorage.get('AMZ'));
  var give = 0;
  
  if (amzAssets / 2 > 0) {
    give = amzAssets / 2;
    LocalContractStorage.del('AMZ');
    LocalContractStorage.set('AMZ', JSON.stringify(amzAssets / 2));
  }
  
  var userInfo = {
    address: address,
    giveId: [],
    token: [{
      tokenName: 'AMZ',
      tokenNum: give
    }]
  };
  
  LocalContractStorage.set(address, JSON.stringify(userInfo));
}

AMZ.prototype.give = function (tokenName, total, itemNum) {
  var defaultGiveList = JSON.parse(LocalContractStorage.get('giveList'));
  var giveList = Object.prototype.toString.call(defaultGiveList) == '[object Array]' ? defaultGiveList : [];
  
  var address = Blockchain.transaction.from;
  var userInfo = JSON.parse(LocalContractStorage.get(address));
  var isState = false;
  for (var i = 0; i < userInfo.token.length; i++) {
    if (userInfo.token[i].tokenName === tokenName && +userInfo.token[i].tokenNum >= +total) {
      isState = true;
      userInfo.token[i].tokenNum = userInfo.token[i].tokenNum - total;
      
      LocalContractStorage.del(address);
      LocalContractStorage.set(address, JSON.stringify(userInfo));

      giveList.push({
        tokenName: tokenName,
        itemNum: itemNum,
        allNum: total,
        surplus: total,
        id: Blockchain.transaction.timestamp
      });
        
      if (giveList.length > 1) {
          LocalContractStorage.del('giveList');
      };
      LocalContractStorage.set('giveList', JSON.stringify(giveList));
    }
  }

  if (!isState) {
    throw new Error("Sorry, your credit is running low")
  }
}

AMZ.prototype.getGive = function () {
  return LocalContractStorage.get('giveList');
}

AMZ.prototype.receiveGive = function (tokenName, id) {
  var giveList = JSON.parse(LocalContractStorage.get('giveList'));
  var address = Blockchain.transaction.from;
  var userInfo = JSON.parse(LocalContractStorage.get(address));
  if (userInfo.giveId.indexOf(id) !== -1) {
    throw new Error("Sorry, your Reclaim");
  }
  
  var status = false;
  for (var i = 0; i < giveList.length; i++) {
    if (giveList[i].tokenName === tokenName && giveList[i].surplus - giveList[i].itemNum >= 0) {
      status = true;
      
      giveList[i].surplus = giveList[i].surplus - giveList[i].itemNum;
      var istoken = false;
      for (var y = 0; y < userInfo.token.length; y++) {
        if (userInfo.token[y].tokenName === tokenName) {
          istoken = true;
          userInfo.token[y].tokenNum = +userInfo.token[y].tokenNum + +giveList[i].itemNum;
        }
      }
    
      if (!istoken) {
        userInfo.token.push({ tokenName: tokenName, tokenNum: giveList[i].itemNum })
      }
      userInfo.giveId.push(id);
      LocalContractStorage.del('giveList');
      LocalContractStorage.del(address);
      LocalContractStorage.set('giveList', JSON.stringify(giveList));
      LocalContractStorage.set(address, JSON.stringify(userInfo));
    }
  }

  if (!status) {
    throw new Error("Sorry, error");
  }
}

AMZ.prototype.transaction = function (tokenName, to, price, hash) {
  if (tokenName.toUpperCase() === 'NAS') {
    throw new Error("Do not support NAS transactions");
  }

  var address = Blockchain.transaction.from;
  var userInfo = JSON.parse(LocalContractStorage.get(address));
  var balanceStatus = false;

  for (var i = 0; i < userInfo.token.length; i++) {
    if (userInfo.token[i].tokenName === tokenName.toUpperCase() && userInfo.token[i].tokenNum >= price) {
        balanceStatus = true;
        userInfo.token[i].tokenNum = userInfo.token[i].tokenNum - price
    }
  }

  if (!balanceStatus) {
    throw new Error("Sorry, your credit is running low");
  }

  var toInfo = JSON.parse(LocalContractStorage.get(to));
  if (!toInfo) {
    var give = 0;
    var amzAssets = JSON.parse(LocalContractStorage.get('AMZ'));

    if (amzAssets / 2 > 0) {
      give = amzAssets / 2;
      LocalContractStorage.del('AMZ');
      LocalContractStorage.set('AMZ', JSON.stringify(amzAssets / 2));
    }

    toInfo = {
      address: to,
      giveId: [],
      token: [{
        tokenName: 'AMZ',
        tokenNum: give
      }]
    };
  }


  var toInfoStatus = false
  
  for (var i = 0; i < toInfo.token.length; i++) {
    if (toInfo.token[i].tokenName === tokenName.toUpperCase()) {
      toInfoStatus = true;
      toInfo.token[i].tokenNum = +toInfo.token[i].tokenNum + +price;
    }
  }

  if (!toInfoStatus) {
    toInfo.token.push({
      tokenName: tokenName.toUpperCase(),
      tokenNum: price
    })
  }

  LocalContractStorage.del(to);
  LocalContractStorage.del(address);
  LocalContractStorage.set(address, JSON.stringify(userInfo));
  LocalContractStorage.set(to, JSON.stringify(toInfo));
  LocalContractStorage.set(hash, JSON.stringify({
    hash: hash,
    tokenName: tokenName,
    num: price,
    time: Blockchain.transaction.timestamp * 1000,
    to: to,
    form: address
  }));
}

AMZ.prototype.queryHash = function (hash) {
  return LocalContractStorage.get(hash)
}

AMZ.prototype.createToken = function (tokenName, tokenNum) {
  var tokenArr = JSON.parse(LocalContractStorage.get('tokenArr'))
  if (tokenArr.indexOf(tokenName.toUpperCase()) !== -1) {
    throw new Error("Sorry, The name is occupied");
  }
  var address = Blockchain.transaction.from;
  var userInfo = JSON.parse(LocalContractStorage.get(address));
  userInfo.token.push({
    tokenName: tokenName.toUpperCase(),
    tokenNum: tokenNum
  })
  tokenArr.push(tokenName.toUpperCase());
  LocalContractStorage.del('tokenArr');
  LocalContractStorage.set('tokenArr', JSON.stringify(tokenArr));
  LocalContractStorage.del(address);
  LocalContractStorage.set(address, JSON.stringify(userInfo));
}

module.exports = AMZ;